package com.chukun.gateway.core.processor;

import com.chukun.gateway.common.code.ResponseCode;
import com.chukun.gateway.core.helper.ResponseHelper;
import com.chukun.gateway.core.parallel.disruptor.EventListener;
import com.chukun.gateway.core.request.HttpRequestWrapper;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chukun
 * @version 1.0.0
 * @description 批量的请求处理器
 * @createTime 2023/12/23 20:42
 */
@Slf4j
public class BatchEventListenerProcessor implements EventListener<HttpRequestWrapper> {

    private NettyCoreProcessor nettyCoreProcessor;

    public BatchEventListenerProcessor(NettyCoreProcessor nettyCoreProcessor) {
        this.nettyCoreProcessor = nettyCoreProcessor;
    }

    @Override
    public void onEvent(HttpRequestWrapper event) {
        nettyCoreProcessor.process(event);
    }

    @Override
    public void onException(Throwable ex, long sequence, HttpRequestWrapper event) {
        HttpRequest request = event.getRequest();
        ChannelHandlerContext ctx = event.getCtx();
        try {
            log.error("BatchEventListenerProcessor onException请求写回失败，request:{},errMsg:{} ",request,ex.getMessage(),ex);

            //构建响应对象
            FullHttpResponse fullHttpResponse = ResponseHelper.getHttpResponse(ResponseCode.INTERNAL_ERROR);
            if(!HttpUtil.isKeepAlive(request)){
                ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
            }else{
                fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.writeAndFlush(fullHttpResponse);
            }
        }catch (Exception e){
            log.error("BatchEventListenerProcessor onException请求写回失败，request:{},errMsg:{} ",request,e.getMessage(),e);
        }
    }
}
